package com.opencee.cloud.bpm.service;

import com.opencee.cloud.bpm.sdk.handle.ProcessCallbackHandler;
import com.opencee.cloud.bpm.sdk.model.BpmProcessNotifyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author yadu
 */
@Controller
public class ProcessCallbackController {

    /**
     * 懒加载所有流程处理器
     */
    @Autowired(required = false)
    public List<ProcessCallbackHandler> processCallbackHandlerList;


    /**
     * 处理器执行入口
     *
     * @param result
     */
    public void execute(BpmProcessNotifyResult result) {
        if (processCallbackHandlerList != null && processCallbackHandlerList.size() > 0) {
            for (ProcessCallbackHandler handler : processCallbackHandlerList
            ) {
                if (handler.support(result)) {
                    handler.execute(result);
                }
            }
        }
    }

    /**
     * 业务通知地址
     * @param response
     */
    @RequestMapping("/process/receive")
    public void callback(BpmProcessNotifyResult result, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try (
                PrintWriter pw = response.getWriter()
        ) {
            // 统一执行入口
            this.execute(result);
            // 必须响应 success 否则通知服务器将认为通知失败,并进行重试
            pw.write("success");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
